package cn.com.kh.lark;

import cn.com.kh.HttpClientProxy;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.util.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @projectName: ngsapitask-hst
 * @package: cn.com.kh
 * @className: larkMSGDev
 * @author: LiJT
 * @description: TODO
 * @date: 2023-09-20 16:56
 * @version: 1.0
 */
public class larkMSGDevHST {
    private static final Log log = LogFactory.getLog(larkMSGDevHST.class);
    //这里就是刚才拿到的Webhook的值
    public static final String WebHookUrl = "https://open.feishu.cn/open-apis/bot/v2/hook/fa093cc5-e0ee-486d-a487-b296f2a1d76e";
    public static final String WebHookKey = "x6qCreL64xDvow4nJzv8wd";

    public static void main(String[] args) throws Exception {

        System.out.println(sendMessage("哈哈"));
    }


    public static boolean sendMessage(String msg) throws Exception {
        //请求的JSON数据，这里用map在工具类里转成json格式
        JSONObject json = new JSONObject();
        json.put("msg_type","text");
        JSONObject text = new JSONObject();
        text.put("text","<b>工单提醒</b>\n过河兵工单<at user_id=\"all\">所有人</at>");
        json.put("content",text);

        // 获取签名
        int timestamp = (int) (System.currentTimeMillis() / 1000);
        log.debug("sendMessage timestamp:" + timestamp);
        String sendSign = GenSign(WebHookKey, timestamp);
        log.debug("sendMessage sendSign:" + sendSign);
        json.put("timestamp", timestamp);
        json.put("sign", sendSign);
        log.debug("sendMessage Body:" + json);

        json = JSONObject.fromObject("{\n" + "    \"receive_id\": \"oc_xxx\",\n" + "    \"content\": \"{\\\"text\\\":\\\"<b>bold content<i>, bold and italic content</i></b>\\\"}\",\n" + "    \"msg_type\": \"text\"\n" + "}");

        //发送post请求
        String result = HttpClientProxy.sendPost(WebHookUrl, json.toString(), "", 0);
        log.debug("sendMessage Result:" + result);

        JSONObject resJson = JSONObject.fromObject(result);

        if (resJson.getInt("StatusCode") == 0) {
            return true;
        } else {

            return false;
        }

    }

    private static String GenSign(String secret, int timestamp) throws NoSuchAlgorithmException, InvalidKeyException {
        //把timestamp+"\n"+密钥当做签名字符串
        String stringToSign = timestamp + "\n" + secret;
        //使用HmacSHA256算法计算签名
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(stringToSign.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(new byte[]{});
        return new String(Base64.encodeBase64(signData));
    }
}
